import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_first_one/components/image_animation.dart';
import 'package:get/get.dart';
import 'dart:async';
import 'package:flutter_first_one/util/config.dart';
// 录音、音频插件
import 'package:flutter_sound/flutter_sound.dart';
// 手机存储路径插件
import 'package:path_provider/path_provider.dart';
import 'package:flutter_first_one/util/permission.dart';
import 'package:flutter_first_one/util/socket.dart';

class Mike extends StatefulWidget {
  const Mike({super.key});

  void methodToTrigger(int type, [List<int>? list]) {
    _MikeState().methodToTrigger(type, list);
  }

  @override
  // ignore: library_private_types_in_public_api
  _MikeState createState() => _MikeState();
}

class _MikeState extends State<Mike> {
  // 初始化音频对象
  FlutterSoundPlayer playerModule = FlutterSoundPlayer();
  // 初始化录音对象
  FlutterSoundRecorder recorderModule = FlutterSoundRecorder();
  // 录音文件路径
  String? _recorderFilePath;

  int myNum = 0;

  void methodToTrigger(int type, [List<int>? list]) {
    if (type == 1) {
      print('开始长按');
    } else if (type == 2) {
      print('按压移动$list');
    } else if (type == 3) {
      print('结束长按');
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    print('mike页面初始化');
    // 获取麦克风权限
    PermissionController.GetMicrophonePermission();
  }

  startRecorder() async {
    // 获取麦克风权限
    bool isGet = await PermissionController.GetMicrophonePermission();
    if (!isGet) return; // 没有权限
    //用户允许使用麦克风之后开始录音
    var tempDir = await getTemporaryDirectory();
    var time = DateTime.now().millisecondsSinceEpoch;
    _recorderFilePath = '${tempDir.path}/$time${ext[Codec.aacADTS.index]}';
    print(tempDir);
    print('路径$_recorderFilePath');
    // 开启录音对象（还没录音）
    await recorderModule.openRecorder();
    //这里我录制的是aac格式的，还有其他格式（开启录音）
    await recorderModule.startRecorder(
        toFile: _recorderFilePath,
        codec: Codec.aacADTS,
        bitRate: 8000,
        numChannels: 1,
        sampleRate: 8000,
        bufferSize: 5);

    recorderModule.onProgress!.listen((e) {
      print(e);
    });
  }

  overRecorder() async {
    // 结束录音
    await recorderModule.stopRecorder();
    // 关闭录音对象
    await recorderModule.closeRecorder();
  }

  playAac() async {
    // 播放aac格式的音频
    if (_recorderFilePath!.isEmpty) return;
    await playerModule.openPlayer();
    await playerModule.startPlayer(
      fromURI: _recorderFilePath,
      whenFinished: () {
        print('播放结束');
      },
    );
  }

  late MySocket socket;
  socketConnect() {
    print('123');
    socket = MySocket();
  }

  socketSend() {
    socket.socketSend({
      'type': 'START',
      'data': {
        'appid': 40800969,
        'appkey': 'EAxHASuU0hC7HrG3DZRs34lu',
        'dev_pid': 1537, // 识别模型，比如普通话还是英语，是否要加标点等
        'cuid': 'erstory-2023-01', // 随便填不影响使用。机器的mac或者其它唯一id，页面上计算UV用。
        'format': 'pcm',
        'sample': 16000
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('儿时故事'),
      ),
      body: Stack(
        children: [
          // 背景图片
          Container(
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: NetworkImage(
                    '${FileConfig.fileDomain}/static/mascot/mascot-bg.jpg'),
                fit: BoxFit.cover,
              ),
            ),
          ),

          // 小虎哥动画
          const Center(
            child: ImageAnimation(),
          ),

          // 内容区域
          Positioned(
              left: 0,
              right: 0,
              bottom: 30,
              child: Container(
                color: Colors.yellow,
                child: Column(
                  children: [
                    ElevatedButton(
                        onPressed: () {
                          startRecorder();
                        },
                        child: Text('录音')),
                    ElevatedButton(
                        onPressed: () {
                          overRecorder();
                        },
                        child: Text('结束')),
                    ElevatedButton(
                        onPressed: () {
                          playAac();
                        },
                        child: Text('播放')),
                    ElevatedButton(
                        onPressed: () {
                          socketConnect();
                        },
                        child: Text('socket链接')),
                    ElevatedButton(
                        onPressed: () {
                          socketSend();
                        },
                        child: Text('socket发送')),
                  ],
                ),
              ))
        ],
      ),
    );
  }
}
